using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Threading.Tasks;
using Zhao.IServer.Log;
using Zhao.IServer.Settlement;

namespace Zhao.Arena.Utility.QuartZJob
{
    /// <summary>
    /// 自动结算任务
    /// </summary>
    public class AutoSettlementJob : IJob
    {
        private readonly ILogsServer _logger;
        private readonly ISettlementService _settlementService;

        public AutoSettlementJob(
            ILogsServer logger,
            ISettlementService settlementService)
        {
            _logger = logger;
            _settlementService = settlementService;
        }

        /// <summary>
        /// 执行自动结算任务
        /// </summary>
        /// <param name="context">任务上下文</param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                await _logger.Info("开始执行每日自动结算任务");

                // 计算昨天的日期（自动结算默认处理前一天的订单）
                DateTime settlementDate = DateTime.Now.Date.AddDays(-1);

                // 执行结算流程
                var result = await _settlementService.ExecuteSettlementAsync(settlementDate);

                // 记录结算结果
                await _logger.Info($"每日自动结算任务完成：结算日期={settlementDate:yyyy-MM-dd}，结算成功数量={result.SuccessfulCount}，失败数量={result.FailedCount}，结算总金额={result.TotalAmount}");
            }
            catch (Exception ex)
            {
                await _logger.Error( $"执行每日自动结算任务时发生错误,错误信息:{ex.Message}");
                throw; // 重新抛出异常以便Quartz可以处理作业失败
            }
        }
    }
}